package com.k2data.k2app.service;

import com.k2data.k2app.common.MyConstant;
import com.k2data.k2app.domain.deviceRest.MonitorLimitValue;
import com.k2data.k2app.domain.po.JobTaskDO;
import com.k2data.k2app.domain.po.TaskDTO;
import com.k2data.k2app.domain.vo.Job;
import com.k2data.k2app.service.pas04.Pas04ResultService;
import com.k2data.k2app.service.pas14.Job14Service;
import com.k2data.k2app.util.JsonUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 预警处理
 * Created by clb on 17-4-18.
 */
@Log4j2
@Service
public class JobService {
    @Autowired
    private Pas04ResultService pas04ResultService;
    @Autowired
    private JobTaskService jobTaskService;
    @Autowired
    private  KmxService kmxService;
    @Autowired
    private EarlyWarningService earlyWarningService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private Job14Service jobService;
    @Autowired
    private DeviceService deviceService;
    /**
     *  获取单个job
     *
     * @return
     */
    public Job  get (Long jobId) throws Exception {
        Job job = jobService.get(jobId);
        if(job != null && job.getJobId()!=null && job.getTaskId()!=null){
            Job job1 = withTask(job);
            return job1;
        }
        return job;
    }

    /**
     * 查询和本项目相关的所有jobs
     *
     * owner= '项目_copy' 运行的作业
     */
    public List<Job> listJobs(Long taskId,Long modelId,Integer pageNum,Integer pageSize,Long jobId) throws Exception{
        Map<String,Object> params = getJobParam(taskId,modelId,pageNum,pageSize,jobId);
        params.put("owner",jobService.getOwner()+"_copy");
        List<Job> list = jobService.listByParam(params);
        List<Job> jobs = new ArrayList<>();
         for(Job job:list){
             Job job1 = withTask(job);
             if(job1 != null){
                 jobs.add(job);
             }
         }
        return jobs;
    }

    /**
     * 先查询本地作业记录,再查询
     * @param taskId
     * @param modelId
     * @param pageNum
     * @param pageSize
     * @param jobId
     * @return
     * @throws Exception
     */
    public List<Job> listJobs2(Long taskId,Long modelId,Integer pageNum,Integer pageSize,Long jobId) throws Exception{
        List<Job> jobs = new ArrayList<>();
        JobTaskDO jobTaskDO = new JobTaskDO();
        jobTaskDO.setTaskId(taskId);
        jobTaskDO.setProjectId(modelId);
        jobTaskDO.setJobId(jobId);
        List<JobTaskDO> jobTaskDOs = jobTaskService.queryList(jobTaskDO);
        for(JobTaskDO  jobTaskDO1:jobTaskDOs){
            Job job = jobService.get(jobTaskDO1.getJobId());
            Job job1 = withTask(job);
            jobs.add(job1);
        }
        return jobs;
    }
    public Integer selectCount(Long taskId,Long modelId,Long jobId){
        JobTaskDO jobTaskDO = new JobTaskDO();
        jobTaskDO.setTaskId(taskId);
        jobTaskDO.setProjectId(modelId);
        jobTaskDO.setJobId(jobId);
        int i = jobTaskService.selectCount(jobTaskDO);
        return i;
    }

    public List<Job> listJobs(Long taskId,Long modelId) throws Exception{
        Map<String,Object> params = getJobParam(taskId,modelId,null,null,null);
        params.put("owner",jobService.getOwner()+"_copy");
        List<Job> list = jobService.listByParam(params);
        for(Job job:list){
            withTask(job);
        }
        return list;
    }

    /**
     * 所有jobs
     * 不管是不是通过项目启动的作业
     */
    public List<Job> listAllJobs(Long taskId,Long modelId,Integer pageNum,Integer pageSize,Long jobId) throws Exception{
        Map<String,Object> params = getJobParam(taskId,modelId,pageNum,pageSize,jobId);
        List<Job> list = jobService.listByParam(params);
        return list;
    }

    public Map getJobParam(Long taskId,Long modelId,Integer pageNum,Integer pageSize,Long jobId) throws Exception {
        Map<String,Object> params = new HashMap<>();
        if(jobId != null){
            params.put("id",jobId);
        }
        if(pageNum != null){
            params.put("page",pageNum);
        }
        if(pageSize != null){
            params.put("size",pageSize);
        }
        if(modelId != null){
            params.put("projId",modelId);
        }else if(taskId != null){
            TaskDTO taskDO = taskService.get(taskId);
            if(taskDO != null){
                Long modelId1 = taskDO.getModelId();
                params.put("projId",modelId1);
            }
        }
        return params;

    }

    public Job withTask(Job job) throws Exception {
        JobTaskDO jobTaskDO = jobTaskService.getByJobId(job.getJobId());
        //本地数据库没记录,不显示作业
        if(jobTaskDO == null){
            return null;
        }
        job.setTaskId(jobTaskDO.getTaskId());
        job.setTaskName(jobTaskDO.getTaskName());
//		job.setStartTimeWhere(jobTaskDO.getStartTime());
//		job.setEndTimeWhere(jobTaskDO.getEndTime());
        //设备
        TaskDTO taskDTO = taskService.getWithOutDetail(job.getTaskId());
        job.setTask(taskDTO);
        return job;
    }

    /**
     * 结果处理
     *
     * <pre>1 更新任务状态
     * <pre>2 处理任务结果
     * @param id jobid
     * @return status 作业状态（FAILED,SUCCESS)
     */
    public int updateStatus(Long id,String status) throws Exception{
        // 任务状态值
        Integer statusValue = "success".equals(status.toLowerCase())? MyConstant.SUCCESS:MyConstant.FAILED;
        JobTaskDO jobTaskDO = new JobTaskDO();
        jobTaskDO.setStatus(statusValue);
        jobTaskDO.setJobId(id);
        // 修改作业状态
        log.debug("update job status! jobId:"+id+"----status:"+statusValue+"---desc:"+status);
        jobTaskService.updateStatusByJob(jobTaskDO);
        // 获取作业信息
        JobTaskDO jobTaskDO1 = jobTaskService.getByJobId(jobTaskDO.getJobId());
        if(jobTaskDO1 !=null && jobTaskDO1.getStatus()==1){
            if(jobTaskDO1.getTaskDO().getResult() == null){
                return 0;
            }
            /**
             * 判断任务类型,是统计学指标还是预警消息
             * 1 统计性指标写入kmx实时数据
             * 2 预警消息发送通知操作
             */
            if(MyConstant.RESULT_TYPE_WARNING.equals(jobTaskDO1.getTaskDO().getResult().toLowerCase())){
                TaskDTO taskDTO = taskService.getWithOutDetail(jobTaskDO1.getTaskId());
                if(taskDTO!=null){
                    jobTaskDO1.setModelId(taskDTO.getModelId());
                }
                earlyWarningService.dealWaring(jobTaskDO1);
            }else if(MyConstant.RESULT_TYPE_STATISTICAL.equals(jobTaskDO1.getTaskDO().getResult().toLowerCase())){
                // 统计指标
                //1作业是否同步kmx状态，正在同步
                jobTaskDO1.setIsDealKmx(1);
                jobTaskService.updateStatusByJob(jobTaskDO1);
                //2 kmx实时写入
                kmxService.postData(jobTaskDO1);
                //3 修改数据处理kmx状态
                jobTaskDO1.setIsDealKmx(2);
                jobTaskService.updateStatusByJob(jobTaskDO1);
            }else if (MyConstant.RESULT_TYPE_RULES.equals(jobTaskDO1.getTaskDO().getResult().toLowerCase())){
                jobTaskDO1.setIsDealKmx(1);
                jobTaskService.updateStatusByJob(jobTaskDO1);
                //修改阈值规则
                updateDeviceLimitValue(jobTaskDO1);
                jobTaskDO1.setIsDealKmx(2);
                jobTaskService.updateStatusByJob(jobTaskDO1);
            }
        }
        return 0;
    }

    public void updateDeviceLimitValue(JobTaskDO jobTaskDO) throws Exception {
        // 获取接口数据
        List result =  pas04ResultService.getInterfaces(jobTaskDO.getProjectId(), jobTaskDO.getJobId(),null,null,null);
        log.debug("接口数据："+result);
        for(int i = 0;i<result.size();i++){
            // 每一行转换为一个map
            Map<String, Object> job = JsonUtils.convertJsonStrToMap(result.get(i).toString());
            String factory_id = job.get("factory_id").toString();
            String equipment_id = job.get("equipment_id").toString();
            String machine_id = job.get("machine_id").toString();
            String channel_id = job.get("channel_id").toString();
            String deviceNo = factory_id+"_"+equipment_id+"_"+machine_id;
            String varibleId = jobTaskDO.getTaskDO().getKmxVariableName().split("#")[0].split("_")[3];
            List deviceLimitValues = deviceService.getDeviceLimitValues(Long.parseLong(varibleId), deviceNo, Integer.parseInt(channel_id), true);
            for(int j=0;j<deviceLimitValues.size();j++){
                Map limit = (Map) deviceLimitValues.get(j);
                MonitorLimitValue monitorLimitValue = new MonitorLimitValue();
                monitorLimitValue.setId(Long.parseLong(limit.get("id").toString()));
                monitorLimitValue.setValue(Double.parseDouble(job.get("analysisvalue").toString())+Double.parseDouble(limit.get("value").toString()));
                if(limit.get("state") != null && limit.get("state").toString().equals("1")){
                    //如果已经同步，更新同步
                    log.debug("updateLimitAndSyn");
                    log.debug(monitorLimitValue.toString());
                    deviceService.updateLimitValue(monitorLimitValue.getId(),monitorLimitValue,true);
                }else{
                    //没有同步的，只是更新
                    log.debug("updateLimit");
                    deviceService.updateLimitValue(monitorLimitValue.getId(),monitorLimitValue,false);
                }
            }
        }
    }

    /**
     * 删除作业
     * 包含记录
     * @param projId
     * @param projId
     * @return
     * @throws Exception
     */
    public int delete(Long projId,Long jobId) throws Exception{
        //删除关联关系
        jobTaskService.deleteByJobId(jobId);
        //2 删除作业
        jobService.delete(projId,jobId);
        log.debug("作业"+jobId+"删除成功");
        return 1;
    }
    /**
     * 删除作业
     * 不包含记录
     * @param projId
     * @param projId
     * @return
     * @throws Exception
     */
    public int deletePasJob(Long projId,Long jobId) throws Exception{
        //2 删除作业
        jobService.delete(projId,jobId);
        log.debug("作业"+jobId+"删除成功");
        return 1;
    }

    public List listResultData(Long projectId,Long jobId) throws Exception {
        List list = pas04ResultService.getInterfaces(projectId,jobId,null,null,null);
        return list;
    }
}
